package com.apes.scm.masterdata.product.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.product.model.Brand;
import com.apes.scm.masterdata.product.model.BrandType;
import com.apes.scm.masterdata.product.repository.BrandRepository;
import com.apes.scm.masterdata.product.repository.BrandTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：品牌 Service
 *
 * @author HuJianlin
 * @create 2018-03-15 14:35
 */
@Service("brandService")
public class BrandService extends DomainService {

    @Autowired
    BrandRepository brandRepository;

    public Brand save(SimpleRequest request) {
        Brand brand = request.getO(Brand.class);
        brand = brandRepository.saveAndFlush(brand);
        return brand;
    }


    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<Brand> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return brandRepository.findAll(JpaDsl.toCriteria(filters),PageRequest.of(request.get("page"), request.get("size"),sort));
    }

    /**
     * 功能：接收数据中心推送的消息
     *
     * @param request
     */
    public void receiveSave(SimpleRequest request) {
        Map map = request.getMap();
        Brand brand = request.getO(Brand.class);
        brand.setEnName((String) map.get("enName"));
        if (map.containsKey("brandTypeId") && request.get("brandTypeId") != null) {
            BrandType brandType = SpringManager.getBean(BrandTypeRepository.class).findOne((String) request.get("brandTypeId"));
            if (brandType == null) throw new RuntimeException("品牌类别" + request.get("brandTypeId") + "不存在");
            brand.setBrandType(brandType);
        }
        Brand data = brandRepository.findOne(brand.getId());
        if (data!=null) brand.setVersion(data.getVersion());
        brandRepository.saveAndFlush(brand);
    }
}
